﻿using CommunityToolkit.Mvvm.Messaging;
using dpa.Library.Helper;
using dpa.Library.Models;
using SQLite;

namespace dpa.Library.Services;

public class FavoriteStorage(IPreferenceStorage preferenceStorage) : IFavoriteStorage
{
    private const string DbName = "favoritedb.sqlite3";

    private static string PoetryDbPath = PathHelper.GetLocalFilePath(DbName);

    public event EventHandler<FavoriteStorageUpdatedEventArgs>? Updated;

    private SQLiteAsyncConnection _connection;

    private SQLiteAsyncConnection Connection => _connection ??= new SQLiteAsyncConnection(PoetryDbPath);

    public bool IsInitialized =>
        preferenceStorage.Get(FavoriteStorageConstant.VersionKey, 0) == FavoriteStorageConstant.Version;

    public async Task InitializeAsync()
    {
        await Connection.CreateTableAsync<Favorite>();
        preferenceStorage.Set(FavoriteStorageConstant.VersionKey,
            FavoriteStorageConstant.Version);
    }

    public async Task<Favorite> GetFavoriteAsync(int poetryId) =>
        await Connection.Table<Favorite>()
            .FirstOrDefaultAsync(p => p.PoetryId == poetryId);

    public async Task<IEnumerable<Favorite>> GetFavoritesAsync() =>
        await Connection.Table<Favorite>().Where(p => p.IsFavorite)
            .OrderByDescending(p => p.Timestamp).ToListAsync();

    public async Task SaveFavoriteAsync(Favorite favorite)
    {
        favorite.Timestamp = DateTime.Now.Ticks;
        await Connection.InsertOrReplaceAsync(favorite);
        Updated?.Invoke(this, new FavoriteStorageUpdatedEventArgs(favorite));
        //WeakReferenceMessenger.Default.Send(new FavoriteStorageUpdatedEventArgs(favorite));
    }

    public async Task CloseAsync() => await Connection.CloseAsync();
}